<?php

namespace app\common\model;

use think\Model;
use think\Db;
/**
 * 队列中元素，队列票
 * 字段：
 * ticket_id:报单号
 * value：排队的金额
 * ticket_status：这个单子的状态，排队中，已出局；
 * rank：在队列中的序号；
 * out_time：出局的时间（自动设置）
 * 外部关系：
 * line：所在队列
 * user：队列票的拥有者.
 */
class LineTicket extends Model
{
    protected $insert = ['rank' => ''];
    public function line()
    {
        return $this->belongsTo('Line', 'line_id');
    }
    public function user()
    {
        return $this->belongsTo('User', 'user_id');
    }
    public function getTicketIdAttr($value, $data)
    {
        return 'PJ'.str_pad($data['line_ticket_id'],10,'0',STR_PAD_LEFT);
    }
    public function setRankAttr($value, $data)
    {
        if (empty($value)) {
            $c = self::where('line_id', $data['line_id'])->where('ticket_status', '<>', 2)->count();

            return $c + 1;
        } else {
            return $value;
        }
    }
    public static $ticket_status_category = [0 => '排队中', 1 => '已出局', 2 => '被删除'];
    public function getTicketStatusAttr($value)
    {
        return self::$ticket_status_category[$value];
    }
    public function setTicketStatusAttr($value, $data)
    {
        $catedata = array_flip(self::$ticket_status_category);
        $this->out_time = date('Y-m-d H:i:s');
        if ($value == '已出局' and $data['ticket_status'] == 0) {
            $this->line->outed_num = $this->line->outed_num + 1;
            $this->line->outed_range = self::where('line_id', $data['line_id'])->where('ticket_status', '<>', 2)->count();
            $this->line->save();
        }
        if ($value == '被删除') {
			Db::transaction(function(){
				db('line_ticket')->where('line_id', $this->line_id)->where('ticket_status', '<>', 2)->where('rank', '>', $this->rank)->setDec('rank', 1);
			});
			if($this->line->outed_range>=$this->rank)
			{
				$this->line->outed_range = $this->line->outed_range - 1;
				$this->line->save();		
			}

          /*
            $targets = self::where('line_id', $this->line_id)->where('ticket_status', '<>', 2)->where('rank', '>', $this->rank)->select();
            foreach ($targets as $target) {
                $target->rank = $target->rank - 1;
                $target->save();
            }
            */
        }

        return $catedata[$value];
    }
}
